package com.wxq.yaoxia;

import com.droidful.flinggallery.FlingGallery;
import com.wxq.yaoxia.mainborad.YXMainboradActivity;
import com.wxq.yaoxia.util.SharedPreferencesUtil;
import com.wxq.yaoxia.util.YXDBHelper;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class YXLoadingActivity extends YXBaseActivity {

	Handler mHandler = new Handler();
	int localVersion = 2;
	static final String AGREEMENT = "agreement";
	static final String FIRST_SHOW = "first_show";
	RelativeLayout contentLayout;
	private FlingGallery mGallery;
	private final String[] mLabelArray = {  R.drawable.introduce1 + "", 
											R.drawable.introduce2 + "",
											R.drawable.introduce3 + "",
											R.drawable.introduce4 + ""};
	
	@Override
    public boolean onTouchEvent(MotionEvent event)
	{
        return mGallery.onGalleryTouchEvent(event);
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentViewWithTopbar(R.layout.yx_loading, R.layout.yx_topbar);
		contentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
		mGallery = new FlingGallery(this);
		mGallery.setAdapter(
				new ArrayAdapter<String>(getApplicationContext(), 
				android.R.layout.simple_list_item_1, 
				mLabelArray)
				{
					@Override
		        	public View getView(int position, View convertView, ViewGroup parent)
		        	{
		            	if (convertView != null && convertView instanceof GalleryViewItem) {
		            		GalleryViewItem galleryView = (GalleryViewItem) convertView;
			            	galleryView.imageView.setImageResource(Integer.parseInt(mLabelArray[position]));
			            	if (position == mLabelArray.length -1) {
								galleryView.mButton1.setVisibility(View.VISIBLE);
								galleryView.mButton1.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// 进入程序
										GoToMainborad();
									}
								});
							}
			            	else {
			            		galleryView.mButton1.setVisibility(View.GONE);
							}
						}
		            	else
		            	{
		            		convertView = new GalleryViewItem(getApplicationContext(), position);
		                }
		            	return convertView;
		        	}
				});
		mGallery.setIsGalleryCircular(false);
		contentLayout.addView(mGallery, 
				new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT, 
				RelativeLayout.LayoutParams.FILL_PARENT));
		mGallery.setVisibility(View.GONE);
		//装载数据库并且检查是否同意条款，第一次登陆等等。
		setupDatebase();
	}
	
	private class GalleryViewItem extends RelativeLayout
	{
		private ImageView imageView;
		private ImageButton mButton1;

		public GalleryViewItem(Context context, int position)
		{
			super(context);
			this.setLayoutParams(new LinearLayout.LayoutParams(
    				LinearLayout.LayoutParams.MATCH_PARENT,
    				LinearLayout.LayoutParams.MATCH_PARENT));
			this.setBackgroundColor(0xFF000000);
			
			//添加内容View
			imageView = new ImageView(context);
			this.addView(imageView, new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.MATCH_PARENT,
					RelativeLayout.LayoutParams.MATCH_PARENT));
			mButton1 = new ImageButton(context);
            mButton1.setImageResource(R.drawable.welcome_btn);
            mButton1.setScaleType(ScaleType.FIT_XY);
            mButton1.setPadding(0, 0, 0, 0);
            
            RelativeLayout.LayoutParams pl = new RelativeLayout.LayoutParams(
            		200,
            		50);
            pl.addRule(RelativeLayout.CENTER_HORIZONTAL);
            pl.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            pl.setMargins(0, 0, 0, 120);
            this.addView(mButton1,pl); 
            
            
            //设置内部View数据：
            this.imageView.setImageResource(Integer.parseInt(mLabelArray[position]));
        	if (position == mLabelArray.length -1) {
				this.mButton1.setVisibility(View.VISIBLE);
				this.mButton1.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// 进入程序
						GoToMainborad();
					}
				});
			}
        	else {
        		this.mButton1.setVisibility(View.GONE);
			}
		}
	}
	
	public void setupDatebase() {
		new Thread(){

			@Override
			public void run() {
				// 装载数据库和更新文件，如果不存在的话
				YXDBHelper.setupDatabase(YXLoadingActivity.this);
				//YXDBHelper.setupDBUpdateFile(YXLoadingActivity.this);
				checkVersion();
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						checkAgreement();
					}
				});
			}
			
		}.start();
	}
	
	public void GoToMainborad() {
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(YXLoadingActivity.this, YXMainboradActivity.class);
				YXLoadingActivity.this.startActivity(intent);
				finish();
			}
		},500);
	}

	@Override
	public void setTopBarButtonListener() {
		// TODO Auto-generated method stub
		Button leftBtn = (Button) findViewById(R.id.btnLeft);
    	Button rightBtnButton = (Button) findViewById(R.id.btnRight);
    	TextView centerTV = (TextView) findViewById(R.id.centerTV);
    	
    	leftBtn.setVisibility(View.INVISIBLE);
    	rightBtnButton.setVisibility(View.INVISIBLE);
    	centerTV.setVisibility(View.INVISIBLE);
	}

	public void checkVersion() {
		SharedPreferencesUtil spu = new SharedPreferencesUtil(this);
		String versionStr = spu.read(YXUpdateActivity.VERSION);	
		
		if(TextUtils.isEmpty(versionStr))
		{
			spu.save(YXUpdateActivity.VERSION, ""+localVersion);
			
		}
		else {
			localVersion = Integer.parseInt(versionStr);
			Log.d("wxq", "version = "+localVersion);
		}
	}
	
	public void checkAgreement() {
		final SharedPreferencesUtil spu = new SharedPreferencesUtil(this);
		String agree = spu.read(AGREEMENT);
		
		if (! "TRUE".equals(agree)) {
			View agreeView = getLayoutInflater().inflate(R.layout.agreement_diag, null);
			//展示条款页面
			Log.d("wxq", "show agreement");
			AlertDialog ad = new AlertDialog.Builder(this)
			.setTitle("使用条款")
			.setView(agreeView)
			.setPositiveButton("同意", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// 同意的话就写入同意字段
					spu.save(AGREEMENT, "TRUE");
					checkFirstShow();
				}
			})
			.setNegativeButton("不同意", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// 提示用户必须同意
					new AlertDialog.Builder(YXLoadingActivity.this)
					.setTitle("注意")
					.setMessage("必须同意使用条款才可使用本软件!")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							checkAgreement();
						}
					})
					.show();
				}
			}).create();
			ad.show();
		}
		else {
			checkFirstShow();
		}
	}
	
	public void checkFirstShow() {
		SharedPreferencesUtil spu = new SharedPreferencesUtil(this);
		String firstShow = spu.read(FIRST_SHOW);
		if (! "TRUE".equals(firstShow)) {
			//展示滑动介绍页面
			Log.d("wxq", "show introduce");
			mGallery.setVisibility(View.VISIBLE);
			spu.save(FIRST_SHOW, "TRUE");
		}
		else {
			GoToMainborad();
		}
	}
}
